<?php

namespace app\api\service\intelligentlive;

use app\api\model\intelligentlive\Account;
use app\api\model\intelligentlive\Product;
use app\api\model\intelligentlive\Source;
use app\lib\exception\intelligentlive\IntelligentliveException;
use think\Db;
use think\Exception;
use think\Request;

class SourceService
{
    private static $instance;

    public static function getInstance(): SourceService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function addSource($params)
    {
        $info = [
            "link"=>$params['link']??"",
            "model"=>$params['model']??"",
            "recording_time"=>$params['recording_time'],
            "remark"=>$params['remark']??null,
        ];

        $source = Source::where("link",$params['link'])->findOrEmpty();
        if (!$source->isEmpty()){
            throw new IntelligentliveException([
                'msg' => "素材已存在，请勿重复提交",
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        try {
            Source::create($info);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new IntelligentliveException([
                'msg' => "添加失败",
                'error_code' => 20002
            ]);
        }
    }

    public function upSource($params)
    {
        $source = Source::where("id",$params['id'])->findOrEmpty();
        if (!$source->isEmpty()){
            $res = Source::update($params);
            if (!$res) {
                throw new intelligentliveException([
                    'msg' => "更新失败",
                    'error_code' => 20002
                ]);
            }
        } else {
            throw new intelligentliveException([
                'msg' => "素材不存在",
                'error_code' => 20003
            ]);
        }
    }

    public function delSource($params)
    {
        $info = Source::where("id",$params["id"])->findOrEmpty();
        if ($info->isEmpty()){
            throw new intelligentliveException([
                'msg' => '素材不存在',
                'error_code' => 20001
            ]);
        }
        $info->delete();
    }

    public function sourceList($params)
    {
        $pageSize = $params['pageSize']??200;
        $query = Source::field("*");
        if (!empty($params["model"])) {
            $query->where('model',"like","%".$params['model']."%");
        }
        $data = $query->paginate($pageSize);
        return $data;
    }
}